import Author from "../components/Author";
import Authorteacher from "../components/Author_teacher";
import { createPrize } from "@/api/prize";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { getCategoryList, getLevelList, getRankList } from "@/api/rule";
import {
  ScientificPrizeType,
  SubjectType,
  DefaultSubjectType,
  CompleteUnit,
  SumUnitCnt,
  UnitRank,
  FirstLevelDiscipline,
  ProjectScource,
  ResultsForm
} from "@/utils/variable";

export default {
  name: "AddPrize",
  components: { Author, ElImageViewer, Authorteacher },

  data() {
    return {
      PDF_vis: false,
      pageNums: 0,
      pdfurl: null,
      fileListView: [],
      fileData: [], // 保存上传的文件
      sendFormData: new FormData(),
      baseDataFormValidated: false,
      dialogImageUrl: "",
      dialogVisible: false,
      image: "",
      fileList: [],
      departmentList: [],
      hideupload: false,
      // 表单数据
      mediaFormData: {},
      mediaFormDesc: {},
      remarkFormData: {},
      prizecascader: [],
      remarkFormDesc: {
        remarks: {
          type: "textarea",
          label: "备注"
        }
      },
      formData: {},
      formDesc: {
        title: {
          type: "input",
          label: "奖励名称",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        results_name: {
          type: "input",
          label: "成果名称",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        scientific_prize_type: {
          type: "select",
          label: "奖励(科研奖励用)类别",
          required: true,
          options: ScientificPrizeType,
          attrs: {
            filterable: true,
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        people_cnt: {
          type: "number",
          label: "获奖人数",
          required: true,
          attrs: {
            size: "small",
            controls: false
          },
          style: {
            width: "50%"
          },
          layout: 12
        },
        licence_issuing_authority: {
          type: "input",
          label: "发证机关",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        prize_date: {
          type: "date",
          required: true,
          label: "获奖日期",
          attrs: {
            size: "small",
            "value-format": "yyyy-MM-dd"
          },
          style: {
            width: "50%"
          },
          layout: 12
        },
        complete_unit: {
          type: "input",
          label: "完成单位",
          required: true,
          default: CompleteUnit,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        prize_category: {
          type: "select",
          label: "获奖类别",
          required: true,
          options: getCategoryList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        prize_rank: {
          type: "select",
          label: "获奖等级",
          required: true,
          options: getRankList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        prize_level: {
          type: "select",
          label: "获奖级别",
          required: true,
          options: getLevelList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        sum_unit_cnt: {
          type: "select",
          label: "总参加单位数",
          required: false,
          options: SumUnitCnt,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        unit_rank: {
          type: "select",
          label: "单位排名",
          required: false,
          options: UnitRank,
          attrs: {
            size: "small",
            clearable: true
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        authorization_num: {
          type: "input",
          label: "奖励批准号",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        first_level_discipline: {
          type: "select",
          label: "一级学科",
          required: true,
          options: FirstLevelDiscipline,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        project_source: {
          type: "select",
          label: "项目来源",
          required: true,
          options: ProjectScource,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        subject_type: {
          type: "radio",
          label: "学科门类",
          required: true,
          options: SubjectType,
          default: DefaultSubjectType,
          layout: 12
        },
        results_form: {
          type: "select",
          label: "成果形式",
          required: true,
          options: ResultsForm,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        }
      }
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.initData();
      this.addBaseFormCss();
    },
    // 初始化数据
    initData() {
      this.sendFormData = new FormData();
      this.baseDataFormValidated = false;
    },
    // 为基本信息表单添加css
    addBaseFormCss() {
      const form1 = document.getElementById("form1");
      const tmp = form1.childNodes[0].childNodes[0].childNodes[0].childNodes[0];
      var className = tmp.childNodes[0].getAttribute("class") + " first-node";
      tmp.childNodes[0].setAttribute("class", className);
    },

    // 基本信息表单请求前的钩子，阻止请求并把数据添加到结果表单，修改状态为验证通过
    beforeRequestBaseDataForm(data) {
      // var reward_length = data.reward.length;
      // data.reward = data.reward[reward_length - 1];
      for (var i in data) {
        if (data[i] !== undefined) {
          this.sendFormData.append(i, data[i]);
        }
      }
      this.baseDataFormValidated = true;
      return false;
    },

    // 获取子组件--学生信息 验证后的数据
    getAuthorData(data,v) {
      const jsonData = JSON.stringify(data.authorDataList);
      this.sendFormData.append("author_student", jsonData);
      this.author_student_v=v
      if (!v) {
        this.$notify({
          type: "error",
          title: "学生信息错误",
          message: "请填写完整",
          duration: 2000
        });
      }
    },

    // 获取子组件--老师信息 验证后的数据
    getAuthorData1(data,v) {
      const jsonData = JSON.stringify(data.authorDataList);
      this.sendFormData.append("author_teacher", jsonData);
      this.author_teacher_v=v
      if (!v) {
        this.$notify({
          type: "error",
          title: "老师信息错误",
          message: "请填写完整",
          duration: 2000
        });
      }
    },
    
    async commitAuthorData() {
      await this.$refs.author.commitAuthor();
      await this.$refs.authorteacher.commitAuthor();
      // 数据都通过验证，则进行保存操作
      const file_cnt = this.sendFormData.getAll("file").length;
      if (this.baseDataFormValidated && file_cnt > 0&&this.author_teacher_v&&this.author_student_v) {
        this.createData();
      }
    },
    // 新建数据
    createData() {
      const loading = this.$loading({
        lock: true,
        text: "正在处理",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      createPrize(this.sendFormData)
        .then(() => {
          loading.close();
          this.resetForm();
          this.$notify({
            type: "success",
            title: "新建成功",
            message: "新建获奖成功"
          });
        })
        .catch(error => {
          loading.close();
          this.$notify({
            title: "错误",
            message: error.response.data.message,
            type: "error",
            duration: 0
          });
        });
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.fileListView = [file.url];
      this.dialogVisible = true;
    },

    // 上传文件之前的钩子
    beforeUpload(file) {
      const type = file.name.split(".")[1];
      if (["png", "jpg", "jpeg"].indexOf(type) === -1) {
        this.$message.error("只能上传png,jpg,jpeg格式图片");
        return false;
      }
      // 限制文件上传大小, 大于 maxSize M则提示, 且不请求提交表单
      const maxSize = 10;
      const isLtSize = file.size / 1024 / 1024 >= maxSize;
      if (isLtSize) {
        this.$message.error("上传的每个文件大小不能超过" + maxSize + "M");
        return false;
      }
    },

    // 文件列表移除文件的钩子
    handleRemoveFile(file, fileList) {
      this.sendFormData.delete("file");
    },

    // 上传文件事件，将文件添加到formdata
    uploadFile(item) {
      this.sendFormData.append("file", item.file);
    },

    // 保存备注表单前的钩子
    // 保存备注表单也就是提交包括前面的所有表单
    async beforeRequestRemarkForm(data) {
      this.initData();
      for (var i in data) {
        this.sendFormData.append(i, data[i]);
      }
    },

    // 保存备注表单事件, 对其它表单进行提交
    async handleRequestRemarkForm(data) {
      await this.$refs.baseDataForm.handleSubmitForm();
      await this.$refs.upload.submit();
      const file_cnt = this.sendFormData.getAll("file").length;
      if (!file_cnt) {
        this.$notify({
          type: "error",
          title: "附件错误",
          message: "附件必须上传",
          duration: 0
        });
        return
      }
      this.commitAuthorData();
    },

    // 清空所有表单
    resetForm() {
      this.$refs.baseDataForm.resetForm();
      this.$refs.author.authorFormData = this.$refs.author.originFormData;
      this.$refs.upload.clearFiles();
      this.$refs.remarkForm.resetForm();
      this.$router.push({
        name: "PrizeList",
        params: { refresh: true }
      });
    }
  }
};
